﻿using DB2WORD.Logics;
using DB2WORD.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Linq;
using System.Globalization;
using NPOI.SS.Formula.Functions;

namespace DB2WORD
{
    public partial class FrmMore : Form
    {
        public FrmMore()
        {
            InitializeComponent();
            this.btnSaveEdits.Enabled = false;
            this.btnSaveEditColumns.Enabled = false;
            this.Shown += FrmMore_Shown;
        }

        private void FrmMore_Shown(object? sender, EventArgs e)
        {
            this.tables = MainForm.Groups.SelectMany(g => g.Tables ?? Enumerable.Empty<TableInfo>()).ToList();
        }

        private List<TableInfo> tables;
        private List<ColumnInfo> columns = new List<ColumnInfo>();
        private void btnListUnEditTables_Click(object sender, EventArgs e)
        {
            var unconfiguredTables = this.tables
                .Where(t => t.Label.IsEmptyOrLike(t.Name))
                .Select(t => new EditModel
                {
                    TableName = t.Name,
                    CurrentLabel = t.Label,
                    SuggestedLabel = t.Label
                }).ToList();

            this.dataGridView1.Columns[1].Visible = false;
            this.dataGridView1.Columns[2].Visible = false;
            this.dataGridView1.DataSource = unconfiguredTables;
            this.btnSaveEdits.Enabled = true;
            this.btnSaveEditColumns.Enabled = false;
            this.dataGridView1.Refresh();
        }

        private void btnListUnEditColumns_Click(object sender, EventArgs e)
        {
            columns.Clear();
            var unconfiguredColumns = new List<object>();
            foreach(TableInfo t in this.tables)
            {
                columns.AddRange(t.Columns.Where(c => !c.Label.IsEmptyOrLike(c.Name)));
                var cols = t.Columns.Where(c => c.Label.IsEmptyOrLike(c.Name))
                    .Select(c => new EditModel
                    {
                        TableName = t.Name,
                        TableLabel = t.Label,
                        FieldName = c.Name,
                        CurrentLabel = c.Label,
                        SuggestedLabel = GenerateSuggestedLabel(c.Label)
                    }).ToList();
                unconfiguredColumns.AddRange(cols);
            }

            this.dataGridView1.Columns[1].Visible = true;
            this.dataGridView1.Columns[2].Visible = true;
            this.dataGridView1.DataSource = unconfiguredColumns;
            this.dataGridView1.Refresh();
            this.btnSaveEditColumns.Enabled = true;
            this.btnSaveEdits.Enabled = false;
        }

        private void btnSaveEdits_Click(object sender, EventArgs e)
        {
            if(this.dataGridView1.DataSource is DataTable table)
            {
                table.AcceptChanges();
                var list = table.AsList<EditModel>();
                foreach(var t in list)
                {
                    if(!t.SuggestedLabel.IsEmptyOrLike(t.TableName))
                    {
                        var tableinfo = this.tables.FirstOrDefault(x => x.Name == t.TableName);
                        if(tableinfo != null)
                        {
                            tableinfo.Label = t.SuggestedLabel;
                        }
                    }
                }
            }
            this.ShowFrom();
            MessageBox.Show("自动配置完成！");
        }

        private void btnSaveEditColumns_Click(object sender, EventArgs e)
        {
            if(this.dataGridView1.DataSource is DataTable table)
            {
                table.AcceptChanges();
                var list = table.AsList<EditModel>();
                foreach(var t in list)
                {
                    if(!t.SuggestedLabel.IsEmptyOrLike(t.FieldName))
                    {
                        var tableinfo = this.tables.FirstOrDefault(x => x.Name == t.TableName);
                        if(tableinfo != null)
                        {
                            var columninfo = tableinfo.Columns.FirstOrDefault(x => x.Name == t.FieldName);
                            if(columninfo != null)
                            {
                                columninfo.Label = t.SuggestedLabel;
                            }
                        }
                    }
                }
            }
            this.ShowFrom();
            MessageBox.Show("自动配置完成！");
        }


        private string GenerateSuggestedLabel(string name)
        {
            if(string.IsNullOrWhiteSpace(name))
                return name;

            var cols = columns
                .Where(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            if(cols.Any())
            {
                return cols
                    .GroupBy(c => c.Label)
                    .OrderByDescending(x => x.Count())
                    .First()
                    .Key;
            }
            return name;
        }

        public async void ShowFrom()
        {
            var tables = MainForm.Groups.SelectMany(x => x.Tables ?? new List<TableInfo>()).ToList();
            var unNamedTables = tables.Count(x => x.Label.IsEmptyOrLike(x.Name));
            var columns = tables.SelectMany(x => x.Columns ?? new List<ColumnInfo>()).ToList();
            var unNamedColumns = columns.Count(x => x.Label.IsEmptyOrLike(x.Name));
            var indexes = tables.SelectMany(x => x.Indexes ?? new List<IndexInfo>()).ToList();
            var colNames = columns.GroupBy(x => x.Name.ToLower());
            var colNamesCount = colNames.Count();
            var namedColNames = colNames.Count(x => x.Any(c => !c.Label.IsEmptyOrLike(c.Name)));
            var unNamedColNames = colNames.Count(x => x.All(c => c.Label.IsEmptyOrLike(c.Name)));
            var diffLabelColNames = colNames.Count(x => x.Where(c => !c.Label.IsEmptyOrLike(c.Name)).Select(y => y.Label).Distinct().Count() > 1);

            this.btnListDiffLabelColumnNames.Enabled = unNamedColNames > 0;
            this.btnListUnEditColumnNames.Enabled = unNamedColNames > 0;
            this.btnListUnEditColumns.Enabled = unNamedColumns > 0;
            this.btnListUnEditTables.Enabled = unNamedTables > 0;

            this.lblSummary.Text = @$"
总计模块数：{MainForm.Groups.Count}
总计表格数：{tables.Count}
    未维护标签：{unNamedTables}
总计字段数：{columns.Count}
    未维护字段总数：{unNamedColumns}
    字段名称数：{colNamesCount}
        已维护字段名称数：{namedColNames}
        未维护字段名称数：{unNamedColNames}
        存在分歧字段名称数：{diffLabelColNames}
总计索引数：{indexes.Count}
".Trim();
        }
    }
}
